package com.example.demoapp.controller;

import cn.hutool.core.io.FileUtil;
import com.example.demoapp.entity.Employee;
import com.example.demoapp.exception.BusinessException;
import com.example.demoapp.pojo.Result;
import com.example.demoapp.service.EmployeeService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController//标识一个类为RESTful 风格的控制器
@RequestMapping("/employee")//该类下的所有接口都有一个/employee前缀
public class EmployeeController {
    //引用service资源
    @Resource
    private EmployeeService employeeService;

    //    查询
    @GetMapping("/selecAll")
    public Result<Object> selectAll() {
    //    查询数据库的表的内容
        List<Employee> list = employeeService.selecAll();
        return Result.success(list,"success");
    }

    //    根据id查询员工
    @GetMapping("/selecByid")
    public Result<Employee> selecByid(@RequestParam(value = "id",required = true) Integer id,@RequestParam(value = "no",required = false) Integer no) {
        Employee employee = employeeService.selecByid(id);
        return Result.success(employee);
    }

    //分页查询
    @GetMapping("/pageSelect")
    public Result<PageInfo<Employee>> selectByid(@RequestParam(defaultValue = "1") Integer pageNo, @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Employee> pageInfo =  employeeService.pageSelect(pageNo,pageSize);
        return Result.success(pageInfo);
    }

    //  新增员工接口
    @PostMapping("/save")
    public Result<Object> addEmployee(@RequestBody Employee employee) {
        int result = employeeService.save(employee);
        return Result.success(null,result>0?"添加成功":"添加失败");
    }

    //根据id删除员工
    @DeleteMapping("/del")
    public Result<Object> deleteEmployee(@RequestParam Integer id) {
        int result = employeeService.del(id);
        return Result.success(null,result>0?"删除成功":"删除失败");
    }

    //根据id更新数据
    @PostMapping("/update")
    public Result<Object> updateEmployee(@RequestBody Employee employee) {
        int result = employeeService.updata(employee);
        return Result.success(null,result>0?"修改成功":"修改失败");
    }

    //下载文件
    @GetMapping("/download/{fileName}")
    public Result<Object> download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        //找到文件的位置（一般固定一个file文件夹） user.dir为该目录的路径 file为存放文件的文件夹 fileName为前端携带过来要下载的文件名称
        String realPath = System.getProperty("user.dir")+"/file/"+fileName;
        //校验该文件是否存在
        Boolean exist =  FileUtil.exist(realPath);
        if(!exist){
            //抛出错误
            throw new BusinessException(404,"文件不存在");
        }

        //读取文件的字节流 byte[]为将字节流赋值给bytes 数组格式
        byte[] bytes = FileUtil.readBytes(realPath);
        ServletOutputStream os = response.getOutputStream();
        //输出流对象把文件写出到客户端
        os.write(bytes);
        os.flush();
        os.close();
        return Result.success();
    }

    @PostMapping("/upload")
    public Result<Object> upload(@RequestParam("file") MultipartFile file,@RequestParam(value = "id",required = true) Integer id) throws IOException {
        // 1. 定义文件夹路径（只存文件夹，不包含文件名）
        String folderPath = System.getProperty("user.dir") + "/file";
        // 2. 确保文件夹存在（不存在则创建）
        if (!FileUtil.isDirectory(folderPath)) {
            FileUtil.mkdir(folderPath);
        }

        // 3. 生成带时间戳的文件名（避免重复）
        String filename = System.currentTimeMillis() + "-" + file.getOriginalFilename();
        // 4. 拼接完整的文件路径（文件夹+文件名）
        String fullFilePath = folderPath + "/" + filename;

        // 5. 写入文件（使用完整路径！）
        FileUtil.writeBytes(file.getBytes(), fullFilePath);

        // 6. 返回的下载路径要和文件名对应
        String downloadPath = "http://localhost:9090/employee/download/" + filename;

        //将路径存储到对应列的filepath字段中
        employeeService.saveFilepath(downloadPath,id);
        return Result.success(downloadPath, "上传成功");
    }


}
